using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace BlockOS.Client
{
    public class MeshBuilder
    {
        public List<VertexData> m_vertices = new();
        public List<int> m_triangles = new();

        public int VertexCount => m_vertices.Count;

        public MeshBuilder Vertex(Vector3 position, Vector2 texCoord)
        {
            m_vertices.Add(new VertexData(position, texCoord));
            return this;
        }

        public MeshBuilder TriangleIndices(int a, int b, int c)
        {
            m_triangles.Add(a);
            m_triangles.Add(b);
            m_triangles.Add(c);
            return this;
        }

        public MeshBuilder SubVertices(Vector3 offset, params VertexData[] vertices)
        {
            var verticesCpy = vertices.ToArray();
            for (int i = 0; i < vertices.Length; i++) verticesCpy[i].position += offset;
            m_vertices.AddRange(verticesCpy);
            return this;
        }

        public MeshBuilder SubIndices(params int[] indices)
        {
            var indicesCpy = indices.ToArray();
            for (int i = 0; i < indices.Length; i++)
            {
                indicesCpy[i] += VertexCount;
            }
            m_triangles.AddRange(indicesCpy);
            return this;
        }

        public MeshBuilder SubMesh(Vector3 offset, SubMesh<VertexData> mesh)
        {
            SubIndices(mesh.indices);
            SubVertices(offset, mesh.vertices);
            return this;
        }

        public MeshBuilder Clear()
        {
            m_vertices.Clear();
            m_triangles.Clear();
            return this;
        }

        public void WriteMesh(ref Mesh mesh)
        {
            mesh.Clear();
            mesh.vertices = m_vertices.Select(v => v.position).ToArray();
            mesh.uv = m_vertices.Select(v => v.texCoord).ToArray();
            mesh.triangles = m_triangles.ToArray();

            mesh.RecalculateBounds();
            mesh.RecalculateNormals();
        }
    }
}
